package com.favccxx.search.infrastructure.config;

import com.favccxx.search.infrastructure.constant.AuthConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
@Configuration
@EnableSwagger2
public class SwagConfig {

    @GetMapping(path = "/")
    public String swaggerHome() {
        return "redirect:swagger-ui.html";
    }

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeys = new ArrayList<>();
        apiKeys.add(new ApiKey(AuthConstants.APP_KEY, AuthConstants.APP_KEY, "header"));
        apiKeys.add(new ApiKey(AuthConstants.AUTH_TOKEN_KEY, AuthConstants.AUTH_TOKEN_KEY, "header"));
        return apiKeys;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("^(?!auth).*$")).build());
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global",
                "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
        List<ApiKey> apiKeys = this.securitySchemes();
        List<SecurityReference> securityReferences = new ArrayList(apiKeys.size());
        Iterator var5 = apiKeys.iterator();
        while (var5.hasNext()) {
            ApiKey item = (ApiKey) var5.next();
            securityReferences.add(new SecurityReference(item.getName(), authorizationScopes));
        }
        return securityReferences;
    }

}
